import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { ShieldCheck, Users, UserCheck, AlarmClock, Search, Filter, UserMinus, Settings, ShieldAlert, UserPlus } from 'lucide-react'
import { Card, Button, Input, Modal } from '@/components'
import { useThemeStore } from '@/stores/themeStore'
import { useSystemSettingsStore } from '@/stores/systemSettingsStore'
import { useTranslation } from '@/utils/i18n'
import { userAPI, ManagedUserDTO } from '@/utils/api'
import { getUserInfo } from '@/utils/auth'

type UserStatus = 'active' | 'invited' | 'suspended'

interface ManagedUser {
  id: string
  name: string
  username: string
  roleKey: string
  email: string
  phone: string
  department: string
  status: UserStatus
  lastLogin: string
  riskLevel: 'low' | 'medium' | 'high'
}

const statusLabels: Record<UserStatus, { label: string; tone: string }> = {
  active: { label: '正常', tone: 'bg-emerald-50 text-emerald-600 border border-emerald-200' },
  invited: { label: '待激活', tone: 'bg-amber-50 text-amber-600 border border-amber-200' },
  suspended: { label: '已停用', tone: 'bg-rose-50 text-rose-600 border border-rose-200' },
}

const riskTag: Record<'low' | 'medium' | 'high', string> = {
  low: 'bg-emerald-100 text-emerald-700',
  medium: 'bg-amber-100 text-amber-700',
  high: 'bg-rose-100 text-rose-700',
}

const formatDateTime = (value?: string | Date | null) => {
  if (!value) return '—'
  const date = value instanceof Date ? value : new Date(value)
  if (Number.isNaN(date.getTime())) return '—'
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  }).format(date)
}

const mapUserFromDTO = (dto: ManagedUserDTO): ManagedUser => ({
  id: (dto._id as string) || (dto.id ? String(dto.id) : dto.username),
  name: dto.displayName || dto.username,
  username: dto.username,
  roleKey: dto.roleName || 'operator',
  email: dto.email || '',
  phone: dto.phone || '',
  department: dto.department || '',
  status: (dto.status as UserStatus) || 'active',
  lastLogin: dto.lastLoginAt ? formatDateTime(dto.lastLoginAt) : dto.updatedAt ? formatDateTime(dto.updatedAt) : '—',
  riskLevel: (dto.riskLevel as 'low' | 'medium' | 'high') || 'low',
})

const UserList: React.FC = () => {
  const { t } = useTranslation()
  const { settings } = useSystemSettingsStore()
  const themePreference = useThemeStore((state) => state.theme)
  const isDark = useMemo(() => {
    if (themePreference === 'dark') return true
    if (themePreference === 'light') return false
    if (typeof window === 'undefined') return false
    return window.matchMedia('(prefers-color-scheme: dark)').matches
  }, [themePreference])
  const [keyword, setKeyword] = useState('')
  const [roleFilter, setRoleFilter] = useState<'all' | string>('all')
  const [statusFilter, setStatusFilter] = useState<'all' | UserStatus>('all')
  const [users, setUsers] = useState<ManagedUser[]>([])
  const [loading, setLoading] = useState(false)
  const [detailModalOpen, setDetailModalOpen] = useState(false)
  const [permissionModalOpen, setPermissionModalOpen] = useState(false)
  const [riskModalOpen, setRiskModalOpen] = useState(false)
  const [addModalOpen, setAddModalOpen] = useState(false)
  const [selectedUser, setSelectedUser] = useState<ManagedUser | null>(null)
  const [permissionForm, setPermissionForm] = useState({
    roleKey: 'operator',
    status: 'active' as UserStatus,
    department: '',
  })
  const [riskForm, setRiskForm] = useState({
    riskLevel: 'low' as ManagedUser['riskLevel'],
    status: 'active' as UserStatus,
  })
  const [savingPermission, setSavingPermission] = useState(false)
  const [savingRisk, setSavingRisk] = useState(false)
  const [savingAdd, setSavingAdd] = useState(false)
  const [addForm, setAddForm] = useState({
    username: '',
    password: '',
    roleName: 'operator',
    email: '',
    phone: '',
    department: '',
    status: 'invited' as UserStatus,
  })

  const isSuperAdmin = useMemo(() => {
    const info = getUserInfo()
    const role = (info?.roleKey || info?.roleName || '').toLowerCase()
    return role === 'super-admin'
  }, [])

  const roles = useMemo(() => settings.permissions.roles, [settings.permissions.roles])

  const fetchUsers = useCallback(async () => {
    if (!isSuperAdmin) return
    setLoading(true)
    try {
      const response = await userAPI.getUsers({
        keyword: keyword.trim() || undefined,
        roleName: roleFilter === 'all' ? undefined : roleFilter,
      })
      setUsers((response.data?.list || []).map(mapUserFromDTO))
    } catch (error) {
      console.error('加载用户列表失败', error)
    } finally {
      setLoading(false)
    }
  }, [isSuperAdmin, keyword, roleFilter])

  useEffect(() => {
    fetchUsers()
  }, [fetchUsers])

  const summary = useMemo(() => {
    const total = users.length
    const active = users.filter((item) => item.status === 'active').length
    const invited = users.filter((item) => item.status === 'invited').length
    const suspended = users.filter((item) => item.status === 'suspended').length
    const roleDistribution = roles.map((role) => ({
      role,
      count: users.filter((user) => user.roleKey === role.key).length,
    }))

    return { total, active, invited, suspended, roleDistribution }
  }, [users, roles])

  const filteredUsers = useMemo(() => {
    const normalizedKeyword = keyword.trim().toLowerCase()
    return users.filter((user) => {
      const matchKeyword =
        !normalizedKeyword ||
        user.name?.toLowerCase().includes(normalizedKeyword) ||
        user.username?.toLowerCase().includes(normalizedKeyword) ||
        user.email?.toLowerCase().includes(normalizedKeyword) ||
        user.phone?.toLowerCase().includes(normalizedKeyword) ||
        user.department?.toLowerCase().includes(normalizedKeyword)

      const matchRole = roleFilter === 'all' || user.roleKey === roleFilter
      const matchStatus = statusFilter === 'all' || user.status === statusFilter
      return matchKeyword && matchRole && matchStatus
    })
  }, [keyword, users, roleFilter, statusFilter])

  const handleResetFilters = () => {
    setKeyword('')
    setRoleFilter('all')
    setStatusFilter('all')
  }

  const activePercent = summary.total ? Math.round((summary.active / summary.total) * 100) : 0

  const handleOpenDetail = (user: ManagedUser) => {
    setSelectedUser(user)
    setDetailModalOpen(true)
  }

  const handleOpenPermission = (user: ManagedUser) => {
    setSelectedUser(user)
    setPermissionForm({
      roleKey: user.roleKey,
      status: user.status,
      department: user.department,
    })
    setPermissionModalOpen(true)
  }

  const handleOpenRisk = (user: ManagedUser) => {
    setSelectedUser(user)
    setRiskForm({
      riskLevel: user.riskLevel,
      status: user.status,
    })
    setRiskModalOpen(true)
  }

  const closeAllModals = () => {
    setDetailModalOpen(false)
    setPermissionModalOpen(false)
    setRiskModalOpen(false)
    setSelectedUser(null)
  }

  const resetAddForm = useCallback(() => {
    setAddForm({
      username: '',
      password: '',
      roleName: roles[0]?.key || 'operator',
      email: '',
      phone: '',
      department: '',
      status: 'invited',
    })
  }, [roles])

  const handleAddSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    if (!addForm.username.trim() || !addForm.password.trim()) {
      window.alert('请填写用户名和初始密码')
      return
    }
    setSavingAdd(true)
    try {
      await userAPI.createUser({
        username: addForm.username.trim(),
        password: addForm.password,
        roleName: addForm.roleName,
        email: addForm.email.trim() || undefined,
        phone: addForm.phone.trim() || undefined,
        department: addForm.department.trim() || undefined,
        status: addForm.status,
      })
      window.alert('新增成员成功')
      setAddModalOpen(false)
      resetAddForm()
      await fetchUsers()
    } catch (error) {
      console.error('新增成员失败', error)
      window.alert('新增成员失败，请稍后重试')
    } finally {
      setSavingAdd(false)
    }
  }

  if (!isSuperAdmin) {
    return (
      <div className="flex items-center justify-center h-[60vh] text-gray-500 dark:text-gray-300 text-sm">
        当前账号无权访问用户管理，请联系超级管理员开通权限。
      </div>
    )
  }

  const handlePermissionSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    if (!selectedUser) return
    setSavingPermission(true)
    try {
      await userAPI.updateUser(selectedUser.id, {
        roleName: permissionForm.roleKey,
        status: permissionForm.status,
        department: permissionForm.department,
      })
      await fetchUsers()
      closeAllModals()
      window.alert('权限信息已更新')
    } catch (error) {
      console.error('更新用户权限失败', error)
      window.alert('更新权限失败，请稍后重试')
    } finally {
      setSavingPermission(false)
    }
  }

  const handleRiskSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    if (!selectedUser) return
    setSavingRisk(true)
    try {
      await userAPI.updateUser(selectedUser.id, {
        riskLevel: riskForm.riskLevel,
        status: riskForm.status,
      })
      await fetchUsers()
      closeAllModals()
      window.alert('风险控制信息已更新')
    } catch (error) {
      console.error('更新风险控制失败', error)
      window.alert('更新风险控制失败，请稍后重试')
    } finally {
      setSavingRisk(false)
    }
  }

  return (
    <>
    <div className="space-y-6 animate-fade-in">
      <div className="mb-6 animate-slide-up">
        <h2
          className={`text-2xl font-bold mb-2 transition-colors duration-300 ${
            isDark ? 'text-white' : 'text-gray-900'
          }`}
        >
          {t('user.list.title')}
        </h2>
        <p className="text-gray-500 dark:text-gray-400 text-sm">{t('user.list.subtitle')}</p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
        <Card padding="lg" className="bg-gradient-to-br from-blue-500/10 to-blue-500/5 border-blue-100">
          <div className="flex items-center gap-4">
            <div className="p-3 rounded-xl bg-blue-500/20 text-blue-600">
              <Users size={24} />
            </div>
            <div>
              <p className="text-sm text-gray-500">成员总数</p>
              <p className="text-2xl font-semibold text-gray-800">{summary.total}</p>
              <p className="text-xs text-gray-400">覆盖 {summary.roleDistribution.length} 种角色类型</p>
            </div>
          </div>
        </Card>
        <Card padding="lg" className="bg-gradient-to-br from-emerald-500/10 to-emerald-500/5 border-emerald-100">
          <div className="flex items-center gap-4">
            <div className="p-3 rounded-xl bg-emerald-500/20 text-emerald-600">
              <UserCheck size={24} />
            </div>
            <div>
              <p className="text-sm text-gray-500">正常账号</p>
              <p className="text-2xl font-semibold text-gray-800">{summary.active}</p>
              <p className="text-xs text-emerald-500">{activePercent}% 在线</p>
            </div>
          </div>
        </Card>
        <Card padding="lg" className="bg-gradient-to-br from-amber-500/10 to-amber-500/5 border-amber-100">
          <div className="flex items-center gap-4">
            <div className="p-3 rounded-xl bg-amber-500/20 text-amber-600">
              <AlarmClock size={24} />
            </div>
            <div>
              <p className="text-sm text-gray-500">待激活</p>
              <p className="text-2xl font-semibold text-gray-800">{summary.invited}</p>
              <p className="text-xs text-amber-500">建议提醒邀请的账号尽快激活</p>
            </div>
          </div>
        </Card>
        <Card padding="lg" className="bg-gradient-to-br from-rose-500/10 to-rose-500/5 border-rose-100">
          <div className="flex items-center gap-4">
            <div className="p-3 rounded-xl bg-rose-500/20 text-rose-600">
              <UserMinus size={24} />
            </div>
            <div>
              <p className="text-sm text-gray-500">风险账号</p>
              <p className="text-2xl font-semibold text-gray-800">{summary.suspended}</p>
              <p className="text-xs text-rose-500">需复核权限与操作记录</p>
            </div>
          </div>
        </Card>
      </div>

      <Card className="dark:bg-gray-800 dark:border-gray-700">
        <div className="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-4 mb-6">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 flex-1">
            <Input
              label="关键词搜索"
              placeholder="支持姓名、邮箱、电话、部门"
              value={keyword}
              onChange={(event) => setKeyword(event.target.value)}
              leftIcon={<Search size={18} />}
            />
            <div>
              <label className="block text-sm font-semibold text-gray-700 dark:text-gray-200 mb-2">角色筛选</label>
              <div className="relative">
                <select
                  value={roleFilter}
                  onChange={(event) => setRoleFilter(event.target.value)}
                  className="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-xl bg-white dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 dark:text-gray-200 transition-all duration-200"
                >
                  <option value="all">全部角色</option>
                  {roles.map((role) => (
                    <option key={role.key} value={role.key}>
                      {role.name}
                    </option>
                  ))}
                </select>
                <Filter size={16} className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none" />
              </div>
            </div>
            <div>
              <label className="block text-sm font-semibold text-gray-700 dark:text-gray-200 mb-2">状态筛选</label>
              <select
                value={statusFilter}
                onChange={(event) => setStatusFilter(event.target.value as typeof statusFilter)}
                className="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-xl bg-white dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 dark:text-gray-200 transition-all duration-200"
              >
                <option value="all">全部状态</option>
                <option value="active">正常</option>
                <option value="invited">待激活</option>
                <option value="suspended">已停用</option>
              </select>
            </div>
          </div>
          <div className="flex gap-3">
            <Button
              variant="primary"
              size="sm"
              onClick={() => {
                resetAddForm()
                setAddModalOpen(true)
              }}
            >
              <UserPlus size={16} className="mr-1" />
              新增成员
            </Button>
            <Button variant="outline" size="sm" onClick={handleResetFilters}>
              重置
            </Button>
            <Button variant="primary" size="sm" onClick={fetchUsers} loading={loading}>
              刷新列表
            </Button>
          </div>
        </div>

        <div className="overflow-x-auto border border-gray-100 dark:border-gray-700 rounded-2xl">
          <table className="min-w-full divide-y divide-gray-100 dark:divide-gray-700">
            <thead className={isDark ? 'bg-slate-800/70 text-slate-200' : 'bg-gray-50/80 text-gray-600'}>
              <tr>
                <th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider">成员信息</th>
                <th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider">角色与权限</th>
                <th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider">联系方式</th>
                <th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider">组织关系</th>
                <th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider">最近登录</th>
                <th className="px-4 py-3 text-right text-xs font-semibold uppercase tracking-wider">操作</th>
              </tr>
            </thead>
            <tbody className="bg-white dark:bg-gray-800/70 divide-y divide-gray-100 dark:divide-gray-700">
              {loading && (
                <tr>
                  <td colSpan={6} className="px-4 py-10 text-center text-sm text-gray-500 dark:text-gray-400">
                    数据加载中...
                  </td>
                </tr>
              )}
              {!loading &&
                filteredUsers.map((user) => {
                  const roleInfo = roles.find((role) => role.key === user.roleKey)
                  return (
                    <tr
                      key={user.id}
                      className={`transition-colors ${
                        isDark
                          ? 'hover:bg-slate-800/70'
                          : 'hover:bg-gray-50/60'
                      }`}
                    >
                      <td className="px-4 py-4 text-sm">
                        <div className="font-semibold text-gray-800 dark:text-gray-200">{user.name}</div>
                        <div className="text-xs text-gray-400 mt-1">账号 ID：{user.id}</div>
                        <span className={`inline-flex mt-2 px-2.5 py-1 rounded-full text-xs font-medium ${statusLabels[user.status].tone}`}>
                          {statusLabels[user.status].label}
                        </span>
                      </td>
                      <td className="px-4 py-4 text-sm text-gray-700 dark:text-gray-200">
                        <div className="font-semibold flex items-center gap-1">
                          <ShieldCheck size={14} className="text-blue-500" />
                          {roleInfo?.name || '未分配角色'}
                        </div>
                        <div className="text-xs text-gray-400 mt-2 line-clamp-2">{roleInfo?.description}</div>
                        <span className={`inline-flex mt-2 px-2 py-1 rounded-lg text-[11px] font-medium ${riskTag[user.riskLevel]}`}>
                          权限风险：{user.riskLevel === 'high' ? '高' : user.riskLevel === 'medium' ? '中' : '低'}
                        </span>
                      </td>
                      <td className="px-4 py-4 text-sm text-gray-700 dark:text-gray-200">
                        <div>{user.email || '—'}</div>
                        <div className="text-xs text-gray-400 mt-1">{user.phone || '—'}</div>
                      </td>
                      <td className="px-4 py-4 text-sm text-gray-700 dark:text-gray-200">
                        <div>{user.department || '—'}</div>
                      </td>
                      <td className="px-4 py-4 text-sm text-gray-700 dark:text-gray-200">{user.lastLogin}</td>
                      <td className="px-4 py-4 text-sm text-right">
                        <div className="flex items-center justify-end gap-2">
                          <Button variant="outline" size="sm" type="button" onClick={() => handleOpenDetail(user)}>
                            查看
                          </Button>
                          <Button variant="secondary" size="sm" type="button" onClick={() => handleOpenPermission(user)}>
                            调整权限
                          </Button>
                          <Button variant="danger" size="sm" type="button" onClick={() => handleOpenRisk(user)}>
                            风险控制
                          </Button>
                        </div>
                      </td>
                    </tr>
                  )
                })}
              {!loading && !filteredUsers.length && (
                <tr>
                  <td colSpan={6} className="px-4 py-10 text-center text-sm text-gray-500 dark:text-gray-400">
                    暂无匹配的成员，请调整筛选条件或新增成员。
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </Card>

      <Card title="角色与权限说明" className="dark:bg-gray-800 dark:border-gray-700">
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
          {summary.roleDistribution.map(({ role, count }) => (
            <div
              key={role.key}
              className="border border-gray-100 dark:border-gray-700 rounded-2xl p-4 bg-white dark:bg-gray-900/40 space-y-3"
            >
              <div className="flex items-center justify-between">
                <div>
                  <div className="text-sm font-semibold text-gray-800 dark:text-gray-100">{role.name}</div>
                  <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">{role.description}</p>
                </div>
                <span className="text-xs text-blue-500 bg-blue-50 dark:bg-blue-500/10 dark:text-blue-300 px-2.5 py-1 rounded-full">
                  成员 {count} 人
                </span>
              </div>
              <div>
                <p className="text-xs font-semibold text-gray-500">核心权限</p>
                <ul className="mt-2 space-y-1 text-xs text-gray-600 dark:text-gray-300">
                  {role.permissions.slice(0, 4).map((permission) => (
                    <li key={permission} className="flex items-center gap-2">
                      <Settings size={12} className="text-gray-400" />
                      {permission}
                    </li>
                  ))}
                  {role.permissions.length > 4 && <li className="text-gray-400">…</li>}
                </ul>
      </div>
            </div>
          ))}
        </div>
      </Card>
    </div>
    <Modal
      isOpen={detailModalOpen && !!selectedUser}
      onClose={closeAllModals}
      title={selectedUser ? `成员详情 · ${selectedUser.name}` : '成员详情'}
      size="md"
    >
      {selectedUser ? (
        <div className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <p className="text-xs text-gray-500 dark:text-gray-400">账号 ID</p>
              <p className="mt-1 text-sm font-medium text-gray-800 dark:text-gray-100 break-all">{selectedUser.id}</p>
            </div>
            <div>
              <p className="text-xs text-gray-500 dark:text-gray-400">登录账号</p>
              <p className="mt-1 text-sm font-medium text-gray-800 dark:text-gray-100">{selectedUser.username}</p>
            </div>
            <div>
              <p className="text-xs text-gray-500 dark:text-gray-400">角色</p>
              <p className="mt-1 text-sm font-medium text-gray-800 dark:text-gray-100">
                {roles.find((role) => role.key === selectedUser.roleKey)?.name || selectedUser.roleKey}
              </p>
            </div>
            <div>
              <p className="text-xs text-gray-500 dark:text-gray-400">邮箱</p>
              <p className="mt-1 text-sm text-gray-700 dark:text-gray-200">{selectedUser.email || '—'}</p>
            </div>
            <div>
              <p className="text-xs text-gray-500 dark:text-gray-400">电话</p>
              <p className="mt-1 text-sm text-gray-700 dark:text-gray-200">{selectedUser.phone || '—'}</p>
            </div>
            <div>
              <p className="text-xs text-gray-500 dark:text-gray-400">部门</p>
              <p className="mt-1 text-sm text-gray-700 dark:text-gray-200">{selectedUser.department || '—'}</p>
            </div>
            <div>
              <p className="text-xs text-gray-500 dark:text-gray-400">最近登录</p>
              <p className="mt-1 text-sm text-gray-700 dark:text-gray-200">{selectedUser.lastLogin}</p>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <span className={`inline-flex px-3 py-1 rounded-full text-xs font-semibold ${statusLabels[selectedUser.status].tone}`}>
              {statusLabels[selectedUser.status].label}
            </span>
            <span className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-semibold ${riskTag[selectedUser.riskLevel]}`}>
              <ShieldAlert size={14} />
              风险等级：{selectedUser.riskLevel === 'high' ? '高' : selectedUser.riskLevel === 'medium' ? '中' : '低'}
            </span>
          </div>
        </div>
      ) : (
        <div className="text-sm text-gray-500">未找到成员信息</div>
      )}
    </Modal>

    <Modal
      isOpen={permissionModalOpen && !!selectedUser}
      onClose={closeAllModals}
      title="调整成员权限"
      size="md"
    >
      {selectedUser && (
        <form className="space-y-5" onSubmit={handlePermissionSubmit}>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-2">成员</label>
            <div className={`px-4 py-3 rounded-xl border text-sm ${
              isDark
                ? 'border-slate-700/70 bg-slate-800/70 text-slate-100'
                : 'border-gray-200 bg-gray-50 text-gray-700'
            }`}>
              {selectedUser.name}（{selectedUser.email || '无邮箱'}）
      </div>
    </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-2">角色</label>
            <select
              className="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-xl bg-white dark:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 dark:text-gray-100"
              value={permissionForm.roleKey}
              onChange={(event) => setPermissionForm((prev) => ({ ...prev, roleKey: event.target.value }))}
            >
              {roles.map((role) => (
                <option key={role.key} value={role.key}>
                  {role.name}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-2">账号状态</label>
            <select
              className="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-xl bg-white dark:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 dark:text-gray-100"
              value={permissionForm.status}
              onChange={(event) => setPermissionForm((prev) => ({ ...prev, status: event.target.value as UserStatus }))}
            >
              <option value="active">正常</option>
              <option value="invited">待激活</option>
              <option value="suspended">已停用</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-2">所在部门</label>
            <Input
              value={permissionForm.department}
              onChange={(event) => setPermissionForm((prev) => ({ ...prev, department: event.target.value }))}
              placeholder="输入部门名称"
            />
          </div>
          <div className="flex items-center justify-end gap-3 pt-2">
            <Button type="button" variant="outline" onClick={closeAllModals}>
              取消
            </Button>
            <Button type="submit" variant="primary" loading={savingPermission}>
              保存变更
            </Button>
          </div>
        </form>
      )}
    </Modal>

    <Modal
      isOpen={riskModalOpen && !!selectedUser}
      onClose={closeAllModals}
      title="风险控制"
      size="sm"
    >
      {selectedUser && (
        <form className="space-y-5" onSubmit={handleRiskSubmit}>
          <div>
            <p className="text-sm text-gray-600 dark:text-gray-300">
              针对 <span className="font-semibold">{selectedUser.name}</span> 的风险属性进行管理，可调整风险等级或者快速封禁账号。
            </p>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-2">风险等级</label>
            <select
              className="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-xl bg-white dark:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-red-500/40 focus:border-red-400 dark:text-gray-100"
              value={riskForm.riskLevel}
              onChange={(event) => setRiskForm((prev) => ({ ...prev, riskLevel: event.target.value as ManagedUser['riskLevel'] }))}
            >
              <option value="low">低风险</option>
              <option value="medium">中风险</option>
              <option value="high">高风险</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-2">账号状态</label>
            <select
              className="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-xl bg-white dark:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-red-500/40 focus:border-red-400 dark:text-gray-100"
              value={riskForm.status}
              onChange={(event) => setRiskForm((prev) => ({ ...prev, status: event.target.value as UserStatus }))}
            >
              <option value="active">正常</option>
              <option value="invited">待激活</option>
              <option value="suspended">已停用</option>
            </select>
          </div>
          <div className="flex items-center justify-end gap-3 pt-2">
            <Button type="button" variant="outline" onClick={closeAllModals}>
              取消
            </Button>
            <Button type="submit" variant="danger" loading={savingRisk}>
              提交风控
            </Button>
          </div>
        </form>
      )}
    </Modal>

    <Modal
      isOpen={addModalOpen}
      onClose={() => setAddModalOpen(false)}
      title="新增成员"
      size="md"
    >
      <form className="space-y-4" onSubmit={handleAddSubmit}>
        <Input
          label="用户名"
          value={addForm.username}
          onChange={(event) => setAddForm((prev) => ({ ...prev, username: event.target.value }))}
          placeholder="请输入成员登录账号"
          required
        />
        <Input
          label="初始密码"
          type="password"
          value={addForm.password}
          onChange={(event) => setAddForm((prev) => ({ ...prev, password: event.target.value }))}
          placeholder="设置初始密码"
          required
        />
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-2">角色</label>
          <select
            className="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-xl bg-white dark:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 dark:text-gray-100"
            value={addForm.roleName}
            onChange={(event) => setAddForm((prev) => ({ ...prev, roleName: event.target.value }))}
          >
            {roles.map((role) => (
              <option key={role.key} value={role.key}>
                {role.name}
              </option>
            ))}
          </select>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <Input
            label="邮箱"
            type="email"
            value={addForm.email}
            onChange={(event) => setAddForm((prev) => ({ ...prev, email: event.target.value }))}
            placeholder="可选填写"
          />
          <Input
            label="电话"
            value={addForm.phone}
            onChange={(event) => setAddForm((prev) => ({ ...prev, phone: event.target.value }))}
            placeholder="可选填写"
          />
        </div>
        <Input
          label="部门"
          value={addForm.department}
          onChange={(event) => setAddForm((prev) => ({ ...prev, department: event.target.value }))}
          placeholder="如：运营中心"
        />
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-2">账号状态</label>
          <select
            className="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-xl bg-white dark:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 dark:text-gray-100"
            value={addForm.status}
            onChange={(event) => setAddForm((prev) => ({ ...prev, status: event.target.value as UserStatus }))}
          >
            <option value="active">正常</option>
            <option value="invited">待激活</option>
            <option value="suspended">已停用</option>
          </select>
        </div>
        <div className="flex items-center justify-end gap-3 pt-2">
          <Button type="button" variant="outline" onClick={() => setAddModalOpen(false)}>
            取消
          </Button>
          <Button type="submit" variant="primary" loading={savingAdd}>
            确认创建
          </Button>
        </div>
      </form>
    </Modal>
    </>
  )
}

export default UserList
